<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 轮播项
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\model\BannerItem as bannerItemModel;
use app\admin\service\Attachment;
use think\Db;

class BannerItem extends Base
{
  public function lst()
  {
    $model = new bannerItemModel();
    $item = $model::with('banner')->paginate(20);
    $this->assign('item',$item);
    return $this->fetch();
  }

  public function addEdit()
  {
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    $model = new bannerItemModel();
    if($id > 0) {
      //是修改操作
      if($this->request->isPost()) {
        $post = $this->request->post();
        if ($model->save($post,$id)) {
          return $this->success('修改信息成功','bannerItem/lst');
        } else {
          return $this->error('修改失败');
        }
      } else {
        $banner = Db::name('banner')->select();
        $info = Db::name('banner_item')->where('id',$id)->find();
        $this->assign([
         'info' => $info,
         'banner' => $banner,
        ]);
        return $this->fetch();
      }
    } else {
      //是新增操作
      if($this->request->isPost()) {
        $post = $this->request->post();
        if($model->save($post)) {
          return $this->success('添加成功','bannerItem/lst');
        } else {
          return $this->error('添加失败');
        }
      } else {
        $banner = Db::name('banner')->select();
        $this->assign('banner',$banner);
        return $this->fetch();
      }
    }
  }

  public function del()
  {
    if($this->request->isAjax()) {
      $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
      $imgId = Db::name('banner_item')->where('id',$id)->value('img_id');
      $result = Attachment::delete($imgId); // 删除图片
      if($result) {
        if(false == Db::name('banner_item')->where('id',$id)->delete()) {
          return $this->error('删除失败');
        } else {
          return $this->success('删除成功','bannerItem/lst');
        }
      } else {
        $this->error('删除失败');
      }
    }
  }
}
?>